package org.esk.dablog.dao.jdbc;

import org.esk.dablog.dao.StatisticsDAO;
import org.esk.dablog.model.Statistics;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * This class implements Statistics DAO  
 * User: esk
 * Date: 27.12.2006
 * Time: 15:59:39
 * $Id:$
 */
public class StatisticsDAOImpl extends JdbcDaoSupport implements StatisticsDAO {
    private static final String INSERT_QUERY =
            "insert into STAT_LOG " +
                    " (ID, REQUEST_TIME, REMOTE_USER, REMOTE_ADDRESS, REMOTE_HOST, " +
                    " REQUEST_URI, REFERRER_STRING) VALUES ( " +
                    " SEQ_STAT_LOG.nextval, ?, ?, ?, ?, ?, ?)";

    public List<Statistics> listReferers(String localHostName) {
        return getJdbcTemplate().query(" SELECT REQUEST_TIME, REMOTE_USER, REMOTE_ADDRESS, " +
                " REQUEST_URI, REFERRER_STRING FROM STAT_LOG SL " +
                " WHERE SL.REFERRER_STRING NOT LIKE(?) AND SL.REFERRER_STRING IS NOT NULL " +
                " ORDER BY SL.REQUEST_TIME ", new Object[] {localHostName}, ROW_MAPPER);
    }

    private static final RowMapper ROW_MAPPER = new RowMapper() {
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            Statistics stat = new Statistics();
            stat.setDate(rs.getDate("REQUEST_TIME"));
            stat.setUsername(rs.getString("REMOTE_USER"));
            stat.setIp(rs.getString("REMOTE_ADDRESS"));
            stat.setReferer(rs.getString("REFERRER_STRING"));
            stat.setRequestUri(rs.getString("REQUEST_URI"));
            return stat;
        }
    };
}
